var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spread = (this && this.__spread) || function () {
    for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
    return ar;
};
import React, { useMemo, useState, useEffect, useRef, useImperativeHandle } from 'react';
import { View, ScrollView, Text } from '@tarojs/components';
import { AtIcon } from 'taro-ui';
import './index.scss';
import NoData from '../no-data';
import { Fragment } from 'react';
import { shallowEqual } from '../../utils';
/**
 * FlowList 列表展示组件
 */
var FlowList = function (_a, ref) {
    var api = _a.api, apiData = _a.apiData, initData = _a.initData, scrollStyle = _a.scrollStyle, onScroll = _a.onScroll, onScrollClick = _a.onScrollClick, _b = _a.scrollY, scrollY = _b === void 0 ? true : _b, onScrollToUpper = _a.onScrollToUpper, onRefresherPulling = _a.onRefresherPulling, onRefresherRestore = _a.onRefresherRestore, onRefresherRefreshFun = _a.onRefresherRefreshFun, onFetchedData = _a.onFetchedData, renderItem = _a.renderItem, renderListHeaderComponent = _a.renderListHeaderComponent, renderListEmptyComponent = _a.renderListEmptyComponent, renderLoadingComponent = _a.renderLoadingComponent, refresherBackground = _a.refresherBackground, noMoreDataStyle = _a.noMoreDataStyle, _c = _a.isScrollToTop, isScrollToTop = _c === void 0 ? false : _c, _d = _a.hasPopData, hasPopData = _d === void 0 ? false : _d, contentClassName = _a.contentClassName, popDataFunc = _a.popDataFunc, scrollTop = _a.scrollTop;
    var _e = __read(useState(function () {
        return initData ? initData : [];
    }), 2), data = _e[0], setData = _e[1];
    var _f = __read(useState(false), 2), refreshing = _f[0], setRefreshing = _f[1];
    var _g = __read(useState(false), 2), noMoreData = _g[0], setNoMoreData = _g[1];
    var _h = __read(useState(false), 2), hasLoadData = _h[0], setHasLoadData = _h[1];
    var _j = __read(useState(apiData), 2), apiProps = _j[0], setApiProps = _j[1];
    var _k = __read(useState(''), 2), scrollIntoView = _k[0], setScrollIntoView = _k[1];
    var pageNo = useRef(1);
    var loading = useRef(false);
    useEffect(function () {
        if (isScrollToTop) {
            setScrollIntoView('scrollDivTop');
        }
        else {
            setScrollIntoView('');
        }
    }, [isScrollToTop]);
    var onScrollFun = function (e) {
        var top = e.detail.scrollTop;
        if (top < 30) {
            setScrollIntoView('');
        }
        onScroll && onScroll(e);
    };
    useImperativeHandle(ref, function () {
        return {
            refresh: function () {
                onRefresherRefresh();
            },
            getData: function () {
                return data;
            },
            setData: function (res) {
                setData(res);
            }
        };
    });
    useEffect(function () {
        fetchData(true);
    }, [apiProps]);
    useEffect(function () {
        if (!shallowEqual(apiData, apiProps)) {
            setApiProps(apiData);
        }
    }, [apiData, apiProps]);
    var fetchData = function (refresh) { return __awaiter(void 0, void 0, void 0, function () {
        var params, res, _a, res_1;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    if (pageNo.current > 1) {
                        if (loading.current)
                            return [2 /*return*/];
                        loading.current = true;
                    }
                    if (refresh) {
                        pageNo.current = 1;
                    }
                    params = __assign({ pageNo: pageNo.current, pageSize: 20 }, apiData);
                    _b.label = 1;
                case 1:
                    _b.trys.push([1, 4, , 5]);
                    _a = api;
                    if (!_a) return [3 /*break*/, 3];
                    return [4 /*yield*/, api(params)];
                case 2:
                    _a = (_b.sent());
                    _b.label = 3;
                case 3:
                    res = _a;
                    if (!res) {
                        loading.current = false;
                        setRefreshing(false);
                        if (!refresh) {
                            setNoMoreData(true);
                        }
                        else {
                            setHasLoadData(true);
                        }
                    }
                    else {
                        res && afterFetchData(res);
                        loading.current = false;
                    }
                    return [3 /*break*/, 5];
                case 4:
                    res_1 = _b.sent();
                    loading.current = false;
                    setRefreshing(false);
                    setHasLoadData(true);
                    if (!refresh) {
                        setNoMoreData(true);
                    }
                    return [3 /*break*/, 5];
                case 5: return [2 /*return*/];
            }
        });
    }); };
    var afterFetchData = function (res) {
        var resEntities = res && res.entities;
        var fetchData = resEntities && onFetchedData
            ? onFetchedData(res.entities || [], res)
            : null;
        var entities = fetchData || resEntities || [];
        var extData = [];
        if (pageNo.current === 1) {
            extData = __spread(entities);
            setNoMoreData(false);
        }
        else {
            extData = __spread(data, entities);
        }
        //  后台返回的数据有可能会少于pageSize但还有下一页数据
        if (entities.length < 20) {
            setNoMoreData(true);
        }
        else {
            pageNo.current++;
        }
        setData(extData);
        setHasLoadData(true);
        if (hasPopData) {
            popDataFunc && popDataFunc(extData);
        }
        setRefreshing(false);
    };
    var handleLoadMore = function () {
        if (loading.current || noMoreData) {
            return;
        }
        fetchData(false);
    };
    var onRefresherRefresh = function () {
        onRefresherRefreshFun && onRefresherRefreshFun();
        setRefreshing(true);
        fetchData(true);
    };
    var renderLoadingComponentDefault = function () {
        return (React.createElement(View, { className: "loading-wrap" },
            React.createElement(AtIcon, { className: "loading-icon", value: "loading-3", size: "32", color: "#aaa" }),
            React.createElement(Text, { className: "loading-text" }, "\u52A0\u8F7D\u4E2D\u2026")));
    };
    var renderListFooterComponent = function () {
        if (!hasLoadData) {
            return renderLoadingComponent
                ? renderLoadingComponent()
                : renderLoadingComponentDefault();
        }
        if (!data.length)
            return null;
        return (React.createElement(View, { className: "no-more", style: noMoreDataStyle }, noMoreData ? '没有更多了' : '内容加载中...'));
    };
    var renderRowItem = useMemo(function () {
        if (data.length > 0) {
            return data.map(function (item, index) {
                return renderItem(item, index);
            });
        }
        else if (data.length == 0 && hasLoadData) {
            if (renderListEmptyComponent) {
                return renderListEmptyComponent();
            }
            else {
                return (React.createElement(NoData, { className: "message-noData", preset: "no-data", content: "\u6682\u65E0\u6570\u636E" }));
            }
        }
        else {
            return React.createElement(Fragment, null);
        }
    }, [data, hasLoadData, renderListEmptyComponent]);
    var renderHeader = useMemo(function () {
        return renderListHeaderComponent && renderListHeaderComponent();
    }, [renderListHeaderComponent]);
    return (React.createElement(View, { className: "flow-list-wrap" },
        React.createElement(ScrollView, { className: "scrollview", scrollWithAnimation: true, style: scrollStyle, scrollY: scrollY, refresherEnabled: true, refresherTriggered: refreshing, refresherBackground: refresherBackground, onRefresherRefresh: onRefresherRefresh, scrollIntoView: scrollIntoView, scrollTop: scrollTop, onRefresherPulling: onRefresherPulling, onRefresherRestore: onRefresherRestore, onScrollToUpper: onScrollToUpper, lowerThreshold: 200, onScroll: function (e) { return onScroll && onScrollFun(e); }, onScrollToLower: handleLoadMore, onClick: function (e) { return onScrollClick && onScrollClick(e); } },
            React.createElement(View, { id: "scrollDivTop" }),
            renderHeader,
            React.createElement(View, { className: "list-guest list-guest-common " + contentClassName },
                renderRowItem,
                renderListFooterComponent()))));
};
export default React.forwardRef(FlowList);
